package com.sharp.kernel.mybatis.provider;

import com.sharp.kernel.mybatis.join.JoinProvider;
import com.sharp.kernel.mybatis.join.JoinSqlHelper;
import com.sharp.kernel.mybatis.join.entity.JoinRelationship;
import org.apache.ibatis.mapping.MappedStatement;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

/**
 * Title: OuterJoinSelectProvider
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2022/7/26 15:29
 */
public class OuterJoinSelectProvider extends JoinProvider {

    public OuterJoinSelectProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    public String selectCountByExample(MappedStatement ms) {
        Class<?> entityClass = this.getEntityClass(ms);
        StringBuilder sql = new StringBuilder("SELECT ");
        if (this.isCheckExampleEntityClass()) {
            sql.append(SqlHelper.exampleCheck(entityClass));
        }
        sql.append(SqlHelper.exampleCountColumn(entityClass));
        sql.append(JoinSqlHelper.fromJoinTable(entityClass, JoinRelationship.Type.LEFT_JOIN));
        sql.append("\nUNION\n");
        sql.append(" SELECT ");
        if (this.isCheckExampleEntityClass()) {
            sql.append(SqlHelper.exampleCheck(entityClass));
        }
        sql.append(SqlHelper.exampleCountColumn(entityClass));
        sql.append(JoinSqlHelper.fromJoinTable(entityClass, JoinRelationship.Type.RIGHT_JOIN));
        sql.append(SqlHelper.exampleWhereClause());
        sql.append(SqlHelper.exampleForUpdate());
        return sql.toString();
    }

    public String outerJoinSelectByExample(MappedStatement ms) {
        Class<?> entityClass = this.getEntityClass(ms);
        this.setResultType(ms, entityClass);
        StringBuilder sql = new StringBuilder();
        outerJoinSelectByExample(sql, JoinRelationship.Type.LEFT_JOIN, entityClass);
        sql.append("\nUNION\n");
        outerJoinSelectByExample(sql, JoinRelationship.Type.RIGHT_JOIN, entityClass);
        return sql.toString();
    }

    private void outerJoinSelectByExample(StringBuilder sql, JoinRelationship.Type type, Class<?> entityClass) {
        sql.append("SELECT ");
        if (this.isCheckExampleEntityClass()) {
            sql.append(SqlHelper.exampleCheck(entityClass));
        }
        sql.append("<if test=\"distinct\">distinct</if>");
        sql.append(JoinSqlHelper.exampleSelectColumns(entityClass));
        sql.append(JoinSqlHelper.fromJoinTable(entityClass, type));
        sql.append(SqlHelper.exampleWhereClause());
        sql.append(SqlHelper.exampleOrderBy(entityClass));
        sql.append(SqlHelper.exampleForUpdate());
    }

}
